#!usr/bin/env python
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tap_connector23_hana.py
@version:
@time: 2022/01/13 
"""
import pyhdb
from TapClientConnector.connector.tap_connector01_mysql import *


class TAPHanaConnector(TAPConnectorBase):

    def __init__(self, kwargs):
        super().__init__(kwargs)
        self.FORMAT_DB_INFO.pop('database')
        self.connector = pyhdb.connect(**self.FORMAT_DB_INFO)

    def _query(self, sql):
        cursor = self.connector.cursor()
        try:
            cursor.execute(sql)
        except Exception:
            raise SQLError
        res = list(cursor.fetchall())
        self.table_description = cursor.description
        cursor.close()
        return res

    @connector_exec_logger
    def _exec(self, sql):
        cursor = self.connector.cursor()
        try:
            cursor.execute(sql)
        except Exception:
            raise SQLError

    @connector_query_logger
    def show_tables(self) -> list:
        user = self.DB_INFO.get('database_name')
        query_str = f"select * from SYS.M_TABLES where SCHEMA_NAME='{user}'"
        table_list = []
        for i in self._query(query_str):
            table_list.append(i[1])
        return table_list

    # ***** Generate *****

    # ** DDL **

    @generate_logger
    def generate_create(self, table_column, table=None):
        """
        通过表名，字段 类型生成建表语句
        :param table:
        :param table_column:
        :return:
        """
        if table:
            self.CURRENT_TABLE = table
        return f"""
                CREATE TABLE 
               {self.connector_database}."{self.CURRENT_TABLE}" 
               {table_column}"""

    @generate_logger
    def generate_drop(self, table=None):
        if table:
            self.CURRENT_TABLE = table
        return f'DROP TABLE {self.connector_database}."{self.CURRENT_TABLE}"'

    # ** DML **

    @generate_logger
    def generate_insert(self, insert, table=None, ):
        """
        :param table:  table
        :param insert: [columns, values] | [values]
        :return:
        """
        if table:
            self.CURRENT_TABLE = table
        if len(insert) == 1:
            return f"""
                    INSERT INTO
                    {self.connector_database}."{self.CURRENT_TABLE}"
                    VALUES ({insert[0]})"""
        if len(insert) == 2:
            return f"""
                    INSERT INTO
                    {self.connector_database}."{self.CURRENT_TABLE}" ({insert[0]})
                    VALUES ({insert[1]})"""

    @generate_logger
    def generate_update(self, update, where, table=None):
        """
        :param table:
        :param update: {column: value}
        :param where: WHERE ...
        :return:
        """
        if table:
            self.CURRENT_TABLE = table
        _update_list = [f'{k}={v}' for k, v in update.items()]
        COLUMNS = ",".join(_update_list)
        return f"""
               UPDATE 
               {self.connector_database}."{self.CURRENT_TABLE}"
               SET {COLUMNS} {where}"""

    @generate_logger
    def generate_delete(self, where, table=None):
        """
        :param table:
        :param where:
        :return:
        """
        if table:
            self.CURRENT_TABLE = table
        return f"""
                DELETE FROM
                {self.connector_database}."{self.CURRENT_TABLE}" {where}
                """

    @generate_logger
    def generate_select(self, column='*', where='', table=None):
        if table:
            self.CURRENT_TABLE = table
        return f"""
                SELECT {column} FROM
                {self.connector_database}."{self.CURRENT_TABLE}" {where}
                """
